import React, { useState,useEffect } from 'react';
import { Menu, type MenuProps } from 'antd';
import { menuRoute, type RouteMenuItem } from '@/router'
import { useLocation, useNavigate } from "react-router-dom";
import { useEnvStore } from '@/stores/env';
import { useShallow } from 'zustand/react/shallow';
import i18n from '@/locales'

type MenuItem = Required<MenuProps>['items'][number];

const App: React.FC = () => {
  useEnvStore(useShallow((state) => ({
    langName: state.langName,
  })))
  const navigate = useNavigate()
  const location = useLocation()
  const [route, setRoute] = useState<RouteMenuItem[]>(menuRoute())
  useEffect(() => {
    i18n.on('languageChanged', () => {
      setRoute(menuRoute())
    })
    return () => {
      i18n.off('languageChanged')
    }
  }, [])
  const onClick: MenuProps['onClick'] = (e) => {
    navigate(e.key)
  };
  // const toMenuItem=(routes:RouteMenuItem[])=>{
  //   const items: MenuItem[] = []
  //   for (let route of routes) {
  //     items!.push({
  //       label: route.title,
  //       key: route.path,
  //       icon: route.icon,
  //       // 存在子菜单则递归
  //       children: route.children ? toMenuItem(route.children) : undefined,
  //     })
  //   }
  //   return items
  // }
  const toMenuItem = (routes: RouteMenuItem[], parentKey = ''): MenuItem[] =>
    routes.map(route => ({
      label: route.title,
      key: parentKey ? `${parentKey}/${route.path}` : route.path,
      icon: route.icon,
      children: route.children ? toMenuItem(route.children, `${parentKey}/${route.path}`) : undefined,
    }));


  return (
    <section className='flex flex-col w-full h-full'>
      {/* <section className='flex justify-center items-center h-10'>
        logo
      </section> */}
      <Menu className='grow'
        onClick={onClick}
        defaultSelectedKeys={[location.pathname?.split('/')?.at(-1) ?? '']}
        mode="inline"
        items={toMenuItem(route)}
      />
    </section>
  );
};

export default App;